<?php

namespace App\Repositories\Article;


use App\Models\Article\Comment;
use App\Models\Article\CommentAnswer;
use App\Repositories\Repository;
use App\Services\CategoryService;
use Illuminate\Support\Facades\DB;


/**
 *
 */
class CommentRepository extends Repository
{


    public function __construct()
    {

    }

    public function index()
    {
        return Comment::with('answers')->orderBy("created_at", "desc")->paginate(10);
    }

    /**
     *
     * list
     * @author Paco
     * @createTime 2018/5/19 17:36
     * @param $article_id
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list($article_id)
    {
        $rs = Comment::with('answers')
            ->where('article_id', $article_id)
            ->orderBy("created_at", "desc")
            ->paginate(10);
        $rs = json_decode(json_encode($rs), true);
        if ($rs['data']) {
            $cat_service = new CategoryService();
            foreach ($rs['data'] as $k => $v) {
                if ($v['answers']) {
                    $rs['data'][$k]['answers'] = $cat_service->getTree($v['answers']);
                }
            }
        }
        return $rs;
    }


    /**
     *
     * store
     * @author Paco
     * @createTime 2018/5/19 17:38
     * @param $data
     * @return mixed
     */
    public function store($data)
    {
        try {
            Comment::create($data);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10701);
        }
    }

    public function save($data)
    {
        $comment = Comment::find($data['id']);
        if ($comment) {
            try {
                $comment->fill($data)->save();
                return $this->respondSuccess();
            } catch (\Exception $e) {
                return $this->respondError(10106);
            }
        }
        return $this->respondError(10106);
    }

    public function del($id)
    {
        DB::beginTransaction();
        try {
            Comment::where("id", "=", $id)->delete();
            CommentAnswer::where("comment_id", "=", $id)->delete();
            DB::commit();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->respondError(10107);
        }
    }


    /*
     * ==========================================================================================
     *                                    私有方法
     * ==========================================================================================
    */

}

